/* =========================================================
   ЕГЭ НАЛЕГКЕ — ГЛАВНАЯ СТРАНИЦА ТРЕНИНГОВ V3

   Что делает:
   1. Сортирует тренинги по описанию.
   2. Работает и после внутренних переходов GetCourse.
   3. Повторно собирает главную при возврате.
   4. Убирает класс главной внутри тренинга.
   5. Добавляет ссылку «Тренинги» там, где
      GetCourse сам её не показывает.
   6. Не делает AJAX-запросов.
   ========================================================= */

(function () {
  "use strict";


  if (window.__ENL_TRAINING_HOME_V3__) {
    return;
  }


  window.__ENL_TRAINING_HOME_V3__ = true;


  /* =======================================================
     НАСТРОЙКИ
     ======================================================= */

  const SETTINGS = {

    categories: {

      main: {
        title: "Мои курсы",

        markers: [
          "основная подготовка",
          "[section:main]"
        ]
      },


      free: {
        title: "Бесплатный доступ",

        markers: [
          "бесплатное обучение",
          "бесплатный доступ",
          "[section:free]"
        ]
      },


      other: {
        title: "Другие курсы",

        markers: [
          "другие курсы",
          "дополнительные материалы",
          "[section:other]",
          "[section:extra]"
        ]
      }

    }

  };


  /* =======================================================
     ТЕКУЩИЙ ПУТЬ
     ======================================================= */

  function getPath() {

    return window.location.pathname
      .replace(
        /\/+$/,
        ""
      );
  }


  /* =======================================================
     ГЛАВНАЯ СТРАНИЦА ТРЕНИНГОВ?
     ======================================================= */

  function isHomePath(
    path
  ) {

    return (
      path === "/teach/control/stream" ||
      path === "/teach/control/stream/index"
    );
  }


  /* =======================================================
     МЫ ВНУТРИ РАЗДЕЛА ТРЕНИНГОВ?
     ======================================================= */

  function isTrainingPath(
    path
  ) {

    return (
      path.indexOf(
        "/teach/control/stream/"
      ) === 0
    );
  }


  /* =======================================================
     НОРМАЛИЗАЦИЯ ТЕКСТА
     ======================================================= */

  function norm(
    value
  ) {

    return String(
      value || ""
    )
      .replace(
        /ё/g,
        "е"
      )
      .replace(
        /\s+/g,
        " "
      )
      .trim()
      .toLowerCase();
  }


  /* =======================================================
     ПОЛУЧАЕМ ТЕКСТ ОПИСАНИЯ ТРЕНИНГА
     ======================================================= */

  function getDescriptionText(
    row
  ) {

    const link =
      row.querySelector(
        "td > a"
      )
      ||
      row.querySelector(
        "a"
      );


    if (!link) {
      return "";
    }


    const title =
      link.querySelector(
        ".stream-title"
      );


    const divs =
      Array.from(
        link.querySelectorAll(
          "div"
        )
      );


    const texts =
      divs
        .filter(
          function (
            div
          ) {

            /*
             * Название тренинга
             * в описание не включаем.
             */
            if (
              title &&
              (
                div === title ||
                div.contains(
                  title
                )
              )
            ) {

              return false;
            }


            /*
             * Картинка тоже
             * не относится к описанию.
             */
            if (
              div.classList.contains(
                "stream-img"
              )
            ) {

              return false;
            }


            return true;
          }
        )
        .map(
          function (
            div
          ) {

            return String(
              div.textContent || ""
            );
          }
        );


    /*
     * Запасной вариант,
     * если GetCourse поменяет структуру.
     */
    if (!texts.length) {

      let text =
        String(
          link.textContent || ""
        );


      if (title) {

        text =
          text.replace(
            title.textContent || "",
            ""
          );
      }


      return norm(
        text
      );
    }


    return norm(
      texts.join(
        " "
      )
    );
  }


  /* =======================================================
     ОПРЕДЕЛЯЕМ КАТЕГОРИЮ
     ======================================================= */

  function getCategory(
    row
  ) {

    const description =
      getDescriptionText(
        row
      );


    const order = [
      "main",
      "free",
      "other"
    ];


    for (
      let i = 0;
      i < order.length;
      i += 1
    ) {

      const key =
        order[
          i
        ];


      const markers =
        SETTINGS
          .categories[
            key
          ]
          .markers;


      const matched =
        markers.some(
          function (
            marker
          ) {

            return description.includes(
              norm(
                marker
              )
            );
          }
        );


      if (matched) {
        return key;
      }
    }


    /*
     * Без маркера тренинг
     * никогда не исчезает.
     */
    return "other";
  }

/* =======================================================
   КАРТОЧКИ ГОДОВЫХ КУРСОВ
   ======================================================= */

function getMainCourseData(row) {

  const link =
    row.querySelector("td > a") ||
    row.querySelector("a");

  if (!link) {
    return null;
  }


  const nativeTitle =
    link.querySelector(
      ".stream-title"
    );


  const titleText =
    String(
      nativeTitle
        ? nativeTitle.textContent
        : ""
    )
      .replace(/\s+/g, " ")
      .trim();


  /*
   * Берём весь текст ссылки,
   * затем убираем название тренинга.
   *
   * Так не зависим от внутренней
   * HTML-структуры GetCourse.
   */
  let rawDescription =
    String(
      link.innerText ||
      link.textContent ||
      ""
    );


  if (titleText) {

    rawDescription =
      rawDescription.replace(
        titleText,
        ""
      );
  }


  rawDescription =
    rawDescription
      .replace(/\s+/g, " ")
      .trim();


  /*
   * Формат описания:
   *
   * Основная подготовка
   * | предмет
   * | видимое описание
   * | выделяемая часть названия
   */
  const parts =
    rawDescription
      .split("|")
      .map(function (part) {

        return part.trim();
      });


  const subjectText =
    String(
      parts[1] || ""
    )
      .toLowerCase();


  const fullSearchText =
    (
      titleText +
      " " +
      rawDescription
    )
      .toLowerCase();


  let subject = "";


  if (
    subjectText.includes(
      "обществ"
    ) ||
    fullSearchText.includes(
      "обществозн"
    )
  ) {

    subject =
      "obsh";


  } else if (
    subjectText.includes(
      "истор"
    ) ||
    fullSearchText.includes(
      "истор"
    )
  ) {

    subject =
      "hist";
  }


  return {

    link:
      link,

    title:
      titleText,

    subject:
      subject,

    description:
      parts[2] ||
      "готовься к ЕГЭ налегке!",

    accent:
      parts[3] ||
      "ГОДОВОЙ КУРС"

  };
}


/* =======================================================
   СОЗДАЁМ ЗАГОЛОВОК С ЦВЕТНОЙ ПОДЛОЖКОЙ
   ======================================================= */

function createMainCourseTitle(
  titleText,
  accentText
) {

  const title =
    document.createElement(
      "div"
    );


  title.className =
    "enl-main-course-title";


  if (
    !titleText ||
    !accentText
  ) {

    title.textContent =
      titleText;

    return title;
  }


  const lowerTitle =
    titleText.toLowerCase();


  const lowerAccent =
    accentText.toLowerCase();


  const position =
    lowerTitle.indexOf(
      lowerAccent
    );


  /*
   * Если указанной фразы
   * в названии нет —
   * просто показываем название.
   */
  if (position === -1) {

    title.textContent =
      titleText;

    return title;
  }


  const before =
    titleText.slice(
      0,
      position
    );


  const selected =
    titleText.slice(
      position,
      position +
      accentText.length
    );


  const after =
    titleText.slice(
      position +
      accentText.length
    );


  title.appendChild(
    document.createTextNode(
      before
    )
  );


  const accent =
    document.createElement(
      "span"
    );


  accent.className =
    "enl-main-course-accent";


  accent.textContent =
    selected;


  title.appendChild(
    accent
  );


  title.appendChild(
    document.createTextNode(
      after
    )
  );


  return title;
}


/* =======================================================
   ПЕРЕРИСОВЫВАЕМ ГОДОВОЙ КУРС
   ======================================================= */

function decorateMainTraining(
  row
) {

  if (
    row.dataset
      .enlMainCourseReady ===
    "1"
  ) {

    return;
  }


  const data =
    getMainCourseData(
      row
    );


  if (!data) {
    return;
  }


  row.dataset
    .enlMainCourseReady =
    "1";


  row.classList.add(
    "enl-main-course-card"
  );


  if (
    data.subject === "obsh"
  ) {

    row.classList.add(
      "enl-main-course-obsh"
    );


  } else if (
    data.subject === "hist"
  ) {

    row.classList.add(
      "enl-main-course-hist"
    );
  }


  /*
   * Скрываем РОДНОЕ содержимое
   * карточки GetCourse.
   *
   * Саму ссылку не трогаем,
   * поэтому переход в тренинг работает.
   */
  Array
    .from(
      data.link.children
    )
    .forEach(
      function (element) {

        element.classList.add(
          "enl-main-course-native"
        );
      }
    );


  const layout =
    document.createElement(
      "div"
    );


  layout.className =
    "enl-main-course-layout";


  const picture =
    document.createElement(
      "div"
    );


  picture.className =
    "enl-main-course-picture";


  const copy =
    document.createElement(
      "div"
    );


  copy.className =
    "enl-main-course-copy";


  copy.appendChild(
    createMainCourseTitle(
      data.title,
      data.accent
    )
  );


  const description =
    document.createElement(
      "div"
    );


  description.className =
    "enl-main-course-description";


  description.textContent =
    data.description;


  copy.appendChild(
    description
  );


  const logo =
    document.createElement(
      "div"
    );


  logo.className =
    "enl-main-course-logo";


  const go =
    document.createElement(
      "div"
    );


  go.className =
    "enl-main-course-go";


  go.innerHTML =
    '<span class="enl-go-text">перейти</span>' +
    '<span class="enl-go-arrow">→</span>';


  layout.appendChild(
    picture
  );


  layout.appendChild(
    copy
  );


  layout.appendChild(
    logo
  );


  layout.appendChild(
    go
  );


  data.link.appendChild(
    layout
  );
}
    
/* =======================================================
   КАРТОЧКИ БЕСПЛАТНОГО ДОСТУПА
   ======================================================= */

function getFreeCourseData(row) {

  const link =
    row.querySelector("td > a") ||
    row.querySelector("a");

  if (!link) {
    return null;
  }

  const nativeTitle =
    link.querySelector(".stream-title");

  const titleText =
    String(
      nativeTitle
        ? nativeTitle.textContent
        : ""
    )
      .replace(/\s+/g, " ")
      .trim();

  let rawDescription =
    String(
      link.innerText ||
      link.textContent ||
      ""
    );

  if (titleText) {
    rawDescription =
      rawDescription.replace(
        titleText,
        ""
      );
  }

  rawDescription =
    rawDescription
      .replace(/\s+/g, " ")
      .trim();

  /*
   * Формат:
   * Бесплатный доступ
   * | описание
   * | выделяемая фраза
   * | бейдж справа сверху
   * | картинка слева
   */
  const parts =
    rawDescription
      .split("|")
      .map(function (part) {
        return part.trim();
      });

  return {
    link:
      link,

    title:
      titleText,

    description:
      parts[1] ||
      "описание продукта в 1 строку",

    accent:
      parts[2] ||
      "",

    badge:
      parts[3] ||
      "бесплатно!",

    picture:
      parts[4] ||
      ""
  };
}


function decorateFreeTraining(row) {

  if (
    row.dataset
      .enlFreeCourseReady ===
    "1"
  ) {
    return;
  }

  const data =
    getFreeCourseData(row);

  if (!data) {
    return;
  }

  row.dataset
    .enlFreeCourseReady =
    "1";

  row.classList.add(
    "enl-free-course-card"
  );

  Array
    .from(
      data.link.children
    )
    .forEach(function (element) {
      element.classList.add(
        "enl-free-course-native"
      );
    });

  const layout =
    document.createElement("div");
  layout.className =
    "enl-free-course-layout";

  const picture =
    document.createElement("div");
  picture.className =
    "enl-free-course-picture";

  if (data.picture) {
    picture.style.backgroundImage =
      'url("' + data.picture + '")';
  }

  const copy =
    document.createElement("div");
  copy.className =
    "enl-free-course-copy";

  copy.appendChild(
    createMainCourseTitle(
      data.title,
      data.accent
    )
  );

  const description =
    document.createElement("div");
  description.className =
    "enl-free-course-description";
  description.textContent =
    data.description;

  copy.appendChild(
    description
  );

  const badge =
    document.createElement("div");
  badge.className =
    "enl-free-course-badge";
  badge.textContent =
    data.badge;

  const go =
    document.createElement("div");
  go.className =
    "enl-free-course-go";
  go.innerHTML =
    '<span class="enl-go-text">перейти</span>' +
    '<span class="enl-go-arrow">→</span>';

  layout.appendChild(picture);
  layout.appendChild(copy);
  layout.appendChild(badge);
  layout.appendChild(go);

  data.link.appendChild(layout);
}
/* =======================================================
   КАРТОЧКИ «ДРУГИЕ КУРСЫ»
   ======================================================= */

function getOtherCourseData(row) {

  const link =
    row.querySelector("td > a") ||
    row.querySelector("a");

  if (!link) {
    return null;
  }

  const nativeTitle =
    link.querySelector(".stream-title");

  const titleText =
    String(
      nativeTitle
        ? nativeTitle.textContent
        : ""
    )
      .replace(/\s+/g, " ")
      .trim();

  let rawDescription =
    String(
      link.innerText ||
      link.textContent ||
      ""
    );

  if (titleText) {
    rawDescription =
      rawDescription.replace(
        titleText,
        ""
      );
  }

  rawDescription =
    rawDescription
      .replace(/\s+/g, " ")
      .trim();

  /*
   * Формат:
   * Другие курсы
   * | предмет
   * | видимое описание
   * | текст плашки
   */
  const parts =
    rawDescription
      .split("|")
      .map(function (part) {
        return part.trim();
      });

  const subjectText =
    String(parts[1] || "")
      .toLowerCase();

  const fullSearchText =
    (
      titleText +
      " " +
      rawDescription
    ).toLowerCase();

  let subject = "";

  if (
    subjectText.includes("обществ") ||
    fullSearchText.includes("обществозн")
  ) {
    subject = "obsh";
  } else if (
    subjectText.includes("истор") ||
    fullSearchText.includes("истор")
  ) {
    subject = "hist";
  }

  return {
    link:
      link,

    title:
      titleText,

    subject:
      subject,

    description:
      parts[2] ||
      "описание курса",

    badge:
      parts[3] ||
      "кураторам"
  };
}


function decorateOtherTraining(row) {

  if (
    row.dataset
      .enlOtherCourseReady ===
    "1"
  ) {
    return;
  }

  const data =
    getOtherCourseData(row);

  if (!data) {
    return;
  }

  row.dataset
    .enlOtherCourseReady =
    "1";

  row.classList.add(
    "enl-other-course-card"
  );

  if (
    data.subject === "obsh"
  ) {
    row.classList.add(
      "enl-other-course-obsh"
    );
  } else if (
    data.subject === "hist"
  ) {
    row.classList.add(
      "enl-other-course-hist"
    );
  } else {
    row.classList.add(
      "enl-other-course-obsh"
    );
  }

  Array
    .from(
      data.link.children
    )
    .forEach(function (element) {
      element.classList.add(
        "enl-other-course-native"
      );
    });

  const layout =
    document.createElement("div");
  layout.className =
    "enl-other-course-layout";

  const copy =
    document.createElement("div");
  copy.className =
    "enl-other-course-copy";

  const title =
    document.createElement("div");
  title.className =
    "enl-other-course-title";
  title.textContent =
    data.title;

  const description =
    document.createElement("div");
  description.className =
    "enl-other-course-description";
  description.innerHTML =
    data.description;

  copy.appendChild(title);
  copy.appendChild(description);

  const logo =
    document.createElement("div");
  logo.className =
    "enl-other-course-logo";

  const badge =
    document.createElement("div");
  badge.className =
    "enl-other-course-badge";
  badge.textContent =
    data.badge;

  const go =
    document.createElement("div");
  go.className =
    "enl-other-course-go";
  go.innerHTML =
  '<span class="enl-go-text">подробнее</span>' +
  '<span class="enl-go-arrow">→</span>';

  layout.appendChild(copy);
  layout.appendChild(logo);
  layout.appendChild(badge);
  layout.appendChild(go);

  data.link.appendChild(layout);
}
    /* =======================================================
     СОЗДАЁМ ОДИН РАЗДЕЛ
     ======================================================= */

  function createSection(
    key,
    rows,
    originalTable
  ) {

    if (!rows.length) {
      return null;
    }


    const section =
      document.createElement(
        "section"
      );


    section.className =
      "enl-training-section " +
      "enl-training-section--" +
      key;


    const title =
      document.createElement(
        "h2"
      );


    title.className =
      "enl-training-section-title";


    title.textContent =
      SETTINGS
        .categories[
          key
        ]
        .title;


    /*
     * Копируем только оболочку таблицы.
     */
    const table =
      originalTable.cloneNode(
        false
      );


    table.removeAttribute(
      "id"
    );


    table.classList.add(
      "enl-training-table",
      "enl-training-table--" +
        key
    );


    const tbody =
      document.createElement(
        "tbody"
      );
    rows.forEach(
      function (
        row
      ) {

        row.classList.add(
          "enl-training-card"
        );


        /*
         * Новый дизайн годового курса
         * только для раздела «Мои курсы».
         */
        if (
  key === "main"
) {
  decorateMainTraining(
    row
  );
}


if (
  key === "free"
) {
  decorateFreeTraining(
    row
  );
}


if (
  key === "other"
) {
  decorateOtherTraining(
    row
  );
}


        tbody.appendChild(
          row
        );
      }
    );
        
    table.appendChild(
      tbody
    );


    section.appendChild(
      title
    );


    section.appendChild(
      table
    );


    return section;
  }


  /* =======================================================
     КЛАСС ГЛАВНОЙ СТРАНИЦЫ
     ======================================================= */

  function setHomeClass(
    enabled
  ) {

    document.documentElement
      .classList.toggle(
        "enl-training-home",
        enabled
      );


    if (document.body) {

      document.body
        .classList.toggle(
          "enl-training-home",
          enabled
        );
    }
  }


  /* =======================================================
     СОБИРАЕМ ГЛАВНУЮ
     ======================================================= */

  function buildHome() {

    if (
      !isHomePath(
        getPath()
      )
    ) {

      return false;
    }


    setHomeClass(
      true
    );


    /*
     * Если уже собрали —
     * повторно ничего не делаем.
     */
    if (
      document.querySelector(
        ".enl-home-trainings"
      )
    ) {

      return true;
    }


    /*
     * Ищем только исходную таблицу GetCourse.
     *
     * Наши уже созданные таблицы
     * исключаем.
     */
    const tables =
      Array.from(
        document.querySelectorAll(
          ".stream-table"
        )
      );


    const sourceTable =
      tables.find(
        function (
          table
        ) {

          if (
            table.classList.contains(
              "enl-training-table"
            )
          ) {

            return false;
          }


          if (
            table.classList.contains(
              "enl-training-source-hidden"
            )
          ) {

            return false;
          }


          return Boolean(
            table.querySelector(
              "tbody tr"
            )
          );
        }
      );


    /*
     * GetCourse ещё не успел
     * загрузить список.
     */
    if (!sourceTable) {
      return false;
    }


    const sourceBody =
      sourceTable.querySelector(
        "tbody"
      );


    if (!sourceBody) {
      return false;
    }


    const rows =
      Array.from(
        sourceBody.children
      )
      .filter(
        function (
          element
        ) {

          return (
            element.tagName ===
            "TR"
          );
        }
      );


    if (!rows.length) {
      return false;
    }


    /* =====================================================
       ГРУППИРУЕМ
       ===================================================== */

    const groups = {

      main: [],
      free: [],
      other: []

    };


    rows.forEach(
      function (
        row
      ) {

        const key =
          getCategory(
            row
          );


        groups[
          key
        ].push(
          row
        );
      }
    );


    /* =====================================================
       СОЗДАЁМ КОНТЕЙНЕР
       ===================================================== */

    const trainings =
      document.createElement(
        "div"
      );


    trainings.className =
      "enl-home-trainings";


    /*
     * Порядок разделов.
     */
    [
      "main",
      "free",
      "other"
    ].forEach(
      function (
        key
      ) {

        const section =
          createSection(
            key,
            groups[
              key
            ],
            sourceTable
          );


        if (section) {

          trainings.appendChild(
            section
          );
        }
      }
    );


    /*
     * Ставим новый список
     * на место родного списка GetCourse.
     *
     * Баннер и блоки
     * «Настроить вид» не трогаем.
     */
    sourceTable
      .insertAdjacentElement(
        "beforebegin",
        trainings
      );


    /*
     * Исходную таблицу оставляем
     * в DOM, но скрываем.
     */
    sourceTable
      .classList.add(
        "enl-training-source-hidden"
      );


    console.log(
      "[ENL TRAINING HOME V3]",
      {
        main:
          groups.main.length,

        free:
          groups.free.length,

        other:
          groups.other.length
      }
    );


    return true;
  }

/* =======================================================
   ССЫЛКА «ТРЕНИНГИ» ВНУТРИ ТРЕНИНГА

   Логика:
   1. Если GetCourse уже показывает видимую ссылку
      «Тренинги» — используем её.
   2. Меняем её переход на новую главную.
   3. Если ссылки нет — создаём одну свою.
   4. Никогда не допускаем двух ссылок.
   ======================================================= */

function isVisible(
  element
) {

  if (
    !element
  ) {
    return false;
  }


  const style =
    window.getComputedStyle(
      element
    );


  return (
    style.display !== "none" &&
    style.visibility !== "hidden" &&
    style.opacity !== "0" &&
    element.getClientRects().length > 0
  );
}


/* =======================================================
   ИЩЕМ ВИДИМУЮ РОДНУЮ ССЫЛКУ «ТРЕНИНГИ»
   ======================================================= */

function findNativeTrainingLink() {

  const links =
    Array.from(
      document.querySelectorAll(
        "a[href]"
      )
    );


  return (
    links.find(
      function (
        link
      ) {

        /*
         * Нашу собственную ссылку
         * родной не считаем.
         */
        if (
          link.classList.contains(
            "enl-training-list-link"
          )
        ) {
          return false;
        }


        /*
         * Нас интересует именно
         * отдельное слово «Тренинги».
         */
        if (
          norm(
            link.textContent
          ) !==
          "тренинги"
        ) {
          return false;
        }


        /*
         * Скрытые служебные ссылки
         * GetCourse не учитываем.
         */
        return isVisible(
          link
        );
      }
    )
    ||
    null
  );
}


/* =======================================================
   НАСТРАИВАЕМ ССЫЛКУ НАЗАД К ТРЕНИНГАМ
   ======================================================= */

function ensureTrainingBackLink() {

  const path =
    getPath();


  /*
   * Наша собственная ссылка,
   * если она уже была создана.
   */
  const customLinks =
    Array.from(
      document.querySelectorAll(
        ".enl-training-list-link"
      )
    );


  /*
   * На главной списка тренингов
   * такая ссылка вообще не нужна.
   */
  if (
    isHomePath(
      path
    )
  ) {

    customLinks.forEach(
      function (
        link
      ) {

        link.remove();
      }
    );


    return;
  }


  /*
   * Вне тренингов тоже удаляем её.
   */
  if (
    !isTrainingPath(
      path
    )
  ) {

    customLinks.forEach(
      function (
        link
      ) {

        link.remove();
      }
    );


    return;
  }


  /*
   * Ищем ВИДИМУЮ штатную ссылку.
   */
  const nativeLink =
    findNativeTrainingLink();


  /*
   * Если GetCourse сам показывает
   * «Тренинги» — используем эту ссылку.
   */
  if (
    nativeLink
  ) {

    /*
     * Удаляем все наши дубли.
     */
    customLinks.forEach(
      function (
        link
      ) {

        link.remove();
      }
    );


    /*
     * Помечаем родную ссылку,
     * чтобы ниже перехватывать её клик.
     */
    nativeLink.classList.add(
      "enl-training-native-back-link"
    );


    /*
     * И сразу задаём правильный URL.
     */
    nativeLink.setAttribute(
      "href",
      "/teach/control/stream"
    );


    return;
  }


  /*
   * Родной видимой ссылки нет.
   *
   * Если наша уже существует —
   * ничего больше не создаём.
   */
  if (
    customLinks.length
  ) {

    /*
     * На всякий случай оставляем
     * только первую.
     */
    customLinks
      .slice(
        1
      )
      .forEach(
        function (
          link
        ) {

          link.remove();
        }
      );


    return;
  }


  /* =====================================================
     СОЗДАЁМ СВОЮ ССЫЛКУ
     ===================================================== */

  const link =
    document.createElement(
      "a"
    );


  link.className =
    "enl-training-list-link";


  link.href =
    "/teach/control/stream";


  link.textContent =
    "Тренинги";


  /*
   * Лучше всего поставить ссылку
   * непосредственно перед названием тренинга.
   */
  const pageHeader =
    document.querySelector(
      ".page-header"
    );


  if (
    pageHeader
  ) {

    pageHeader.insertAdjacentElement(
      "beforebegin",
      link
    );


    return;
  }


  /*
   * Если стандартного заголовка нет,
   * ищем название тренинга.
   */
  const title =
    document.querySelector(
      "h1"
    );


  if (
    title
  ) {

    title.insertAdjacentElement(
      "beforebegin",
      link
    );


    return;
  }


  /*
   * Последний запасной вариант.
   */
  const container =
    document.querySelector(
      ".main-page-container"
    );


  if (
    container
  ) {

    container.insertBefore(
      link,
      container.firstChild
    );
  }
}
    
  /* =======================================================
     СИНХРОНИЗАЦИЯ СО СТРАНИЦЕЙ
     ======================================================= */

  function syncPage() {

    const path =
      getPath();


    /*
     * На главной включаем её CSS
     * и собираем тренинги.
     */
    if (
      isHomePath(
        path
      )
    ) {

      setHomeClass(
        true
      );


      const customLink =
        document.querySelector(
          ".enl-training-list-link"
        );


      if (customLink) {
        customLink.remove();
      }


      buildHome();


      return;
    }


    /*
     * Ушли с главной —
     * обязательно снимаем её класс.
     */
    setHomeClass(
      false
    );


    ensureTrainingBackLink();
  }


  /* =======================================================
     НЕ ЗАПУСКАЕМ SYNC СОТНИ РАЗ ПОДРЯД
     ======================================================= */

  let syncScheduled =
    false;


  function scheduleSync() {

    if (syncScheduled) {
      return;
    }


    syncScheduled =
      true;


    window.requestAnimationFrame(
      function () {

        syncScheduled =
          false;


        syncPage();
      }
    );
  }


  /* =======================================================
     ЗАПУСК
     ======================================================= */

  function start() {

    /*
     * Проверяем текущую страницу сразу.
     */
    syncPage();
      /*
 * Переход по «Тренинги» делаем
 * обычной полной загрузкой страницы.
 *
 * Это не даёт GetCourse открыть
 * старый список через внутреннюю навигацию.
 */
document.addEventListener(
  "click",
  function (
    event
  ) {

    const link =
      event.target.closest(
        ".enl-training-list-link, " +
        ".enl-training-native-back-link"
      );


    if (
      !link
    ) {
      return;
    }


    event.preventDefault();

    event.stopPropagation();

    event.stopImmediatePropagation();


    window.location.href =
      "/teach/control/stream";
  },
  true
);


    /*
     * GetCourse может менять содержимое
     * без полной перезагрузки страницы.
     *
     * Поэтому наблюдаем только за
     * добавлением/удалением DOM-элементов.
     *
     * characterData НЕ используем.
     */
    const observer =
      new MutationObserver(
        function () {

          scheduleSync();
        }
      );


    observer.observe(
      document.body,
      {
        childList: true,
        subtree: true
      }
    );


    /*
     * Навигация кнопками браузера
     * назад/вперёд.
     */
    window.addEventListener(
      "popstate",
      scheduleSync
    );


    /*
     * Возврат страницы из browser cache.
     */
    window.addEventListener(
      "pageshow",
      scheduleSync
    );
  }


  if (
    document.readyState ===
    "loading"
  ) {

    document.addEventListener(
      "DOMContentLoaded",
      start,
      {
        once: true
      }
    );


  } else {

    start();
  }

})();


/* =========================================================
   ОЖИДАЕМ ЗАГРУЗКУ ШРИФТА NAURYZREDKEDS

   Не показываем сначала системный шрифт,
   а затем резкую подмену.
   ========================================================= */

(function () {
  "use strict";


  if (window.__ENL_NAURYZ_FONT_READY__) {
    return;
  }


  window.__ENL_NAURYZ_FONT_READY__ = true;


  function showTitle() {

    document.documentElement
      .classList.add(
        "enl-nauryz-ready"
      );
  }


  /*
   * Современные браузеры.
   */
  if (
    document.fonts &&
    document.fonts.load
  ) {

    document.fonts
      .load(
        '32px "NauryzRedKeds"'
      )
      .then(
        showTitle
      )
      .catch(
        showTitle
      );


    /*
     * Защита:
     * если файл шрифта не загрузился,
     * текст всё равно покажется.
     */
    window.setTimeout(
      showTitle,
      2000
    );


  } else {

    showTitle();
  }

})();
function fixPrepositions() {

  const selectors = [
    ".enl-main-course-title",
    ".enl-other-course-title",
    ".enl-free-course-title"
  ];

  document.querySelectorAll(
    selectors.join(",")
  ).forEach(function(el){

    el.innerHTML =
      el.innerHTML.replace(
        /\s(в|на|с|по|для|и|к|у|от|до)\s/gi,
        " $1 "
      );

  });

}


setTimeout(
  fixPrepositions,
  1000
);


(function () {

  const DESKTOP_HERO =
"https://fs.getcourse.ru/fileservice/file/download/a/943938/sc/242/h/ce079cbe32540be25ed81d399712be7a.webp";


const MOBILE_HERO =
"https://fs.getcourse.ru/fileservice/file/download/a/943938/sc/172/h/1703f0f39ef20c8011f2b2a81bad09a8.webp";


  function addHeroImage() {

    const banner =
      document.querySelector(
        ".enl-training-home .mHeader"
      );

    if (!banner) return;


    if (
      banner.querySelector(".my-fast-hero")
    ) return;


    const img =
      document.createElement("img");


    img.className =
      "my-fast-hero";


    img.src =
window.innerWidth <= 600
? MOBILE_HERO
: DESKTOP_HERO;


    img.loading =
      "eager";


    img.fetchPriority =
      "high";


    img.decoding =
      "async";


    banner.appendChild(img);

  } // <-- вот здесь закрываем функцию


  addHeroImage();


  document.addEventListener(
    "DOMContentLoaded",
    addHeroImage
  );


})();
